$package("wstuo.role"); 
$import('wstuo.role.functionTree');

/**  
 * @author Van&&Tan  
 * @constructor role
 * @description 角色管理主函数.
 * @date 2011-02-25
 * @since version 1.0 
 */
wstuo.role.role=function(){

	var operator='';
	this.result=null;
	this.roleIds='';
	this.noSelect='';
	this.functionNo='';
	this.editRoleIds='';
	this.optItem='';
	this.str='';
	return{
		/**
		 * @description 状态格式化.
		 * @param cell 当前列值
		 * @param options(下拉选项) 属性
		 */
		roleStateFormat:function(cellvalue, options){
			if(cellvalue)
				return i18n['common_enable'];
			else
				return i18n['common_disable'];
		},
		
		/**
		 * @description 状态格式化.
		 * @param cell 当前列值
		 * @param event 事件
		 * @param data 行数据
		 * @private
		 */
		roleGridFormatter:function(cell,opt,data){
			var actionHTML=$('#roleGridAct').html();
			actionHTML=actionHTML.replace(/\{id}/g,data.roleId);
			return actionHTML;
		},
		
		/**
		 * @description 加载角色列表.
		 */
		showRoleGrid:function(){
			var params = $.extend({},jqGridParams, {	
				url:'role!find.action',
				colNames:['ID',i18n['title_role_roleName'],i18n['title_role_roleCode'],i18n['common_desc'],i18n['common_remark'],i18n['common_state'],i18n['common_action'],'',''],
			 	colModel:[
			 	          {name:'roleId',align:'left',width:30},
			 	          {name:'roleName',align:'left',width:80},
			 	          {name:'roleCode',align:'left',width:80},
			 	          {name:'description',align:'left',width:140,sortable:false},
			 	          {name:'remark',align:'left',width:80,sortable:false},
			 	          {name:'roleState',align:'center',width:30,formatter:wstuo.role.role.roleStateFormat},
			 	          {name:'act',align:'center',sortable:false,width:60,formatter:wstuo.role.role.roleGridFormatter},
			 	          {name:'roleState',hidden:true},
			 	          {name:'dataFlag',hidden:true}
			 	],
				jsonReader: $.extend(jqGridJsonReader, {id: "roleId"}),
				sortname:'roleId',
				pager:'#rolePager'
			});
			$("#roleGrid").jqGrid(params);
			$("#roleGrid").navGrid('#rolePager',navGridParams);
			//列表操作项
			$("#t_roleGrid").css(jqGridTopStyles);
			$("#t_roleGrid").append($('#roleTopMenu').html());
			
			//自适应宽度
			setGridWidth("#roleGrid",15);
			
		},
		
		
		/**
		 * @description 新增窗口.
		 */
		addWin:function(){
			operator="save";
			resetForm("#roleWindowForm");
			$('#roleCode').removeAttr("disabled");
			windows('roleWindow',{title:i18n['title_role_roleSave'],width: 400});
		},
		/** 
		 * @description 新增角色.
		 */
		addRole:function() {
				var ROLE=$('#roleCode').val();
				if(ROLE.indexOf("ROLE_")==-1){
					ROLE="ROLE_"+ROLE;
					$('#roleCode').val(ROLE);
				}
				$.post('role!existByRoleCode.action','roleDto.roleCode='+ROLE,function(data){
					if(data || $('#roleCode').val()==$('#back_roleCode').val()){
						$.post('role!existByRoleName.action','roleDto.roleName='+$('#roleName').val(),function(result){
							 var msg="";
							if(result || $('#roleName').val()==$('#back_roleName').val()){
							
									var role_form = $('#roleWindowForm').serialize();
									var url = 'role!'+operator+'.action';
									$.post(url, role_form, function(){
										$('#roleWindow').dialog('close');
										$('#roleGrid').trigger('reloadGrid');
										if("editRole"===operator)
										       msg=i18n['msg_edit_successful'];
										else
											    msg=i18n['msg_add_successful'];
										 msgShow(msg,"show");
									});
							}else{
								msgShow(i18n['msg_role_roleNameExist'],'show');	
							}
						});
					}else{
						msgShow(i18n['msg_role_roleCodeExist'],'show');	
					}
				});
		},
		
		/** 
		 * @description 删除角色.
		 * @param rowIds 行编号
		 */
		delRole:function(rowIds) {
			if(rowIds==""){	
				msgShow(i18n['msg_atLeastChooseOneData'],'show');
			}else{
				msgConfirm(i18n['msg_msg'],"<br>"+i18n['msg_confirmDelete'], function(){
					var arr = $("#roleGrid").jqGrid("getRowData",rowIds);
					if(arr.dataFlag === "1"){
						msgShow(i18n['msg_canNotDeleteSystemData'],'warning');
						return false;
					}
					var pp = $.param({'ids':rowIds},true);
					$.post("role!deleteRole.action", pp, function(res){
						if(res==0){
							$('#roleGrid').trigger('reloadGrid');
							msgShow(i18n.msg_deleteSuccessful,'show');
						}else if(res==1){
							msgAlert(i18n.msg_canNotDeleteSystemData,'info');					
						}else if(res==2){
							msgAlert(i18n.ERROR_DATA_CAN_NOT_DELETE,'info');
						}
					}, "json");
				});
			}
		},

	

		/** 
		 * @description 编辑角色.
		 * @param rowIds 行编号
		 */
		editRole:function(rowId) {
			operator = 'editRole';
			if(rowId==null){
				msgShow(i18n['msg_atLeastChooseOneData'],'show');
			}else{
				var data = $("#roleGrid").getRowData(rowId);
				if(data.roleCode=='ROLE_ENDUSER' || data.roleCode=='ROLE_SYSADMIN' || data.roleCode=='ROLE_APPROVER' || data.roleCode=='ROLE_ITSOP_MANAGEMENT'){
					msgShow(i18n['msg_system_enduser_role_not_edit'],'show');
				}else{
					var role=' ROLE_CMDBSUPERVISOR ROLE_CHANGECONTROLMANAGER ROLE_PROBLEMMANAGER ROLE_FOURTHLINEENGINEER'
						+'ROLE_SECONDLINEENGINEER ROLE_HELPDESKENGINEER ROLE_HELPDESKTEAMLEADER ROLE_ITSERVICEMANAGER ROLE_THIRDLINEENGINEER' 
						+'ROLE_COMMON_ADMIN ROLE_SUPER_ADMIN_DELEGATE ROLE_SUPER_ADMIN_DELEGATE ROLE_KNOWLEDGEBASEADMIN';
					
					resetForm('#roleWindowForm');
					$('#roleId').val(data.roleId);
					$('#roleName').val(data.roleName);
					
					$('#back_roleCode').val(data.roleCode);
					$('#back_roleName').val(data.roleName);
					$('#remark').val(data.remark);
					$('#role_description').val(data.description);
					if(data.roleState=='false'){
						$('#roleState1').attr("checked",'false')
					}else{
						$('#roleState').attr("checked",'ture');
					}
					if(role.indexOf(data.roleCode) > 0 ){
						$('#roleCode').attr("disabled",'disabled');
						$('#roleCode').val(data.roleCode);
					}else{
						$('#roleCode').removeAttr("disabled");
						$('#roleCode').val(data.roleCode);
					}
					windows('roleWindow',{title:i18n['editRole'],width:450});
				}
			}
		},
		/**
		 * @description 搜索角色.
		 */
		search:function(){
			var sdata=$('#searchRole form').getForm();
			var postData = $("#roleGrid").jqGrid("getGridParam", "postData");       
			$.extend(postData, sdata);
			var _url = 'role!find.action';		
			$('#roleGrid').jqGrid('setGridParam',{url:_url})
				.trigger('reloadGrid',[{"page":"1"}]).jqGrid('setGridParam',{url:_url});
		},
		
		//--------------------------角色权限分配 start-------------------------
		/**
		 * 判断是否是终端用户和系统管理角色
		 * @param rowIds 行编号
		 */
		enduser:function(rowIds){
			
			var result="";
			if(rowIds.length==undefined){
				var _data = $("#roleGrid").getRowData(rowIds);
				if(_data.roleCode=='ROLE_ENDUSER' || _data.roleCode=='ROLE_SYSADMIN' 
					|| _data.roleCode=='ROLE_APPROVER' || _data.roleCode=='ROLE_ITSOP_MANAGEMENT'){
					result=true;
				}
			}else{
				for(var i=0;i<=rowIds.length;i++){
					var data = $("#roleGrid").getRowData(rowIds[i]);
					if(data.roleCode=='ROLE_ENDUSER' || data.roleCode=='ROLE_SYSADMIN' 
						|| data.roleCode=='ROLE_APPROVER' || data.roleCode=='ROLE_ITSOP_MANAGEMENT'){
						result=true;
					}
				}
			}
			
			return result;
		},
		/**
		 * 判断是否是系统管理员
		 * @param rowIds 行编号
		 */
		systeAdminRole:function(rowIds){
			
			var result="";
			if(rowIds.length==undefined){
				var _data = $("#roleGrid").getRowData(rowIds);
				if(_data.roleCode=='ROLE_SYSADMIN' || _data.roleCode=='ROLE_APPROVER'){
					result=true;
				}
			}else{
				for(var i=0;i<=rowIds.length;i++){
					var data = $("#roleGrid").getRowData(rowIds[i]);
					if(data.roleCode=='ROLE_SYSADMIN' || data.roleCode=='ROLE_APPROVER'){
						result=true;
					}
				}
			}
			
			return result;
		},
		
		/**
		 * 判断是否是终端用户
		 * @param rowIds 行编号
		 */
		endUserRole:function(rowIds){
			
			var result=false;
			if(rowIds.length==undefined){
				var _data = $("#roleGrid").getRowData(rowIds);
				if(_data.roleCode=='ROLE_ENDUSER' || _data.roleCode=='ROLE_ITSOP_MANAGEMENT'){
					result=true;
				}
			}else{
				for(var i=0;i<=rowIds.length;i++){
					var data = $("#roleGrid").getRowData(rowIds[i]);
					if(data.roleCode=='ROLE_ENDUSER' || data.roleCode=='ROLE_ITSOP_MANAGEMENT'){
						result=true;
					}
				}
			}
			return result;
		},
		
		/**
		 * @description 打开权限分配窗口
		 * @param rowId    行编号
		 * @param isRoles  是否管理员角色权限
		 */
		open_func:function(rowId,isRoles){
			result=null;
			roleIds=''
			noSelect=''
			optItem='';
			if(rowId==""){
				msgAlert(i18n['msg_atLeastChooseOneData'],'info');
			}else{	
				if(wstuo.role.role.systeAdminRole(rowId)){
					msgAlert(i18n['msg_system_role_not_res_assign'],'info');
				}else{
					if(isRoles){
						$.post('role!getResourceByRoleId.action',"roleId="+rowId,function(data){
							if(data!=null){
								result=data.split(',');
								roleIds=data;
							}else
								result=null;
						})
					}	
					editRoleIds=rowId;
					$('#operationOptions').html(i18n['label_role_chooseFunction']);
					if(wstuo.role.role.endUserRole(rowId))//判断是否是终端用户
						wstuo.role.role.functionTree('Knowledge_Category_View');
					else
						wstuo.role.role.functionTree('');
					windows('assignFunc',{width:660,height:450,open:function(){
						$("#assignFunc").nextAll().remove();
						$("#assignFunc").parent().css("width","660px");
					}});
				}
			}
			
		},
		
		/**
		 * @description 保存权限分配
		 */
		save_func:function(){
			if(result!=null && result!=''){
				str="str="+result+"-"+editRoleIds;
				startProcess();
				$.post('role!setResourceByRoleIds.action',str,function(){
					endProcess();
					$('#assignFunc').dialog('close');
					msgShow(i18n['msg_role_roleSetSuccess'],'show');
				});
			}else{
				msgAlert(i18n['msg_please_ermission'],'info');
			}
			
			
		},
		
		/**
		 * @description 加载操作选
		 * @param event   事件
		 * @param data    数据
		 */
		loadOpertion:function(event, data)
		{
			var resName=data.rslt.obj.attr("resName");
			var resNo=data.rslt.obj.attr("resNo");
			if(resName!=null){
				
				functionNo=resNo;
				wstuo.role.role.optionsByFunId();
			}
		},
		/**
		 * @description 功能TREE
		 * @param resCode 角色代码
		 * */
		functionTree:function (resCode){
			
			wstuo.role.functionTree.functionTreeCallback('#functionTree',resCode,wstuo.role.role.loadOpertion);

		},

		/**
		 * @description 全选
		 * */
	    checkAll:function () {
	    	if($('#checkAll_but')[0].checked){
	    		$('input[name="optItem"]').each(function(){
	    			this.checked=true;
	    		});
	    	}else
	    		$('input[name="optItem"]').each(function(){
	    			this.checked=false;
	    		});
	    	wstuo.role.role.getOptSelect();
	    	
	    },
	    /**
		 * @description 反选
		 * */
	    checkOther:function(){
		    $("input[name='optItem']").each(function() {
		    	if(this.checked == false)
		    		this.checked = true;
		    	else
		    		this.checked = false;
		    })
		    wstuo.role.role.getOptSelect();
	    },
		
	    /**
		 * @description 获取操作项选中的值
		 */
		getOptSelect:function(){
			
			noSelect='';
			$(".optItemId").each(function(){ //由于复选框一般选中的是多个,所以可以循环输出
				if(this.checked){
					if(roleIds=="")
						roleIds=$(this).val();
					else
						roleIds=roleIds+","+$(this).val();
				}else{
					roleIds+=''
					if(noSelect=="")
						noSelect=$(this).val();
					else
					    noSelect=noSelect+","+$(this).val();

				}
			});
			
			
			
			
			/*把数组唯一化*/
			Array.prototype.in_array = function($){
		        for (var i=0;i<this.length;i++ )
		                if(this[i]===$)return true;
		        return false;
			};
			
			Array.prototype.array_unique=function(){
                for (var i = 0, l = this.length,$ = []; i < l; i++)
                        if (!$.in_array(this[i])) $.push(this[i]);
                return $;
			
			};
	
			
			/*把数组指定值删除*/
			Array.prototype.indexOf = function(val) {  
			   for (var i = 0; i < this.length; i++) { 
					   if (this[i] ==val) return i; 
			   }	   
			   return -1;  
			};  
			Array.prototype.remove = function(val) {
				for(var j=0;j<val.length;j++){ 
					var index = this.indexOf(val[j]);  
					if (index > -1) {  
						this.splice(index, 1);
					}    
			    }  
			};
			
			/*清除没选中的值*/
			var noSelectToIds=noSelect.split(',');
			var roleIdsToIds=roleIds.split(',');
			roleIdsToIds=roleIdsToIds.array_unique();
			roleIdsToIds.remove(noSelectToIds);
		
			result=roleIdsToIds.array_unique();
			
			setTimeout(function(){
				roleIds=result
			},0)
			
		},
		
		 /**
		 * @description 根据功能ID加载相应操作
		 */
		optionsByFunId:function(){
			$('#operationOptions').html('');
			$.post("operation!find.action","functionNo="+functionNo+"&rows=10000",function(data){
				var opt=data.data
				if(opt!=""){
					optItem='<table width=100%><tr><td colspan=2>'+
					'<label><input type=checkbox id=checkAll_but onclick=wstuo.role.role.checkAll() /> '+i18n['common_selectAll']+
					'</label>&nbsp;&nbsp;<label><input type=radio name=checkoption id=checkOther_but onclick=wstuo.role.role.checkOther() /> '+i18n['common_deSelect']+'</label></td></tr>';
				}else{
					optItem='<pre>'+i18n.role_msg+'</pre>';
				}
				if(opt!=null)
				{
					for(var i=0; i<opt.length;i++){
						if(i % 2==0){
							optItem=optItem+"<tr>"
						}
						optItem=optItem+"<td><label><input type='checkbox' name='optItem' onclick='wstuo.role.role.getOptSelect()' class='optItemId' "+
						"value='"+opt[i].resNo+"'"
						if(result!=null){
							for(var j=0; j<result.length;j++)
							{	
								if(result[j]==opt[i].resNo)
								{
									optItem=optItem+" checked ";
								}
							}
						}
						optItem=optItem+" /> "+opt[i].resName+"</label></td>"
					}
					optItem+='</table>';
					$('#operationOptions').html(optItem);
				}
			},"json");
		},
		/**
		 * 导出
		 */
		exportRoleView:function(){
			$("#exportRoleForm").submit();
		},
		
		/**
		 * @descriptionadd 导入角色数据
		 * */
		importRoleExcel:function()
		{
			var path=$('#importRoleFile').val();
			if(path!=""){
				startProcess();
				$.ajaxFileUpload({
		            url:'role!importRoleData.action',
		            secureuri:false,
		            fileElementId:'importRoleFile', 
		            dataType:'json',
		            success: function(data,status){
		            	
		            	$('#importUserDataWindow').dialog('close');
		            	if(data=="FileNotFound"){
							msgAlert(i18n['msg_dc_fileNotExists'],'error');
							endProcess();
						}else if(data=="IOError"){
							msgAlert(i18n['msg_dc_importFailure'],'error');
							endProcess();
						}else{
							
							msgAlert(i18n['msg_dc_dataImportSuccessful']
							+'<br>['+
							data
							.replace('Total',i18n['opertionTotal'])
							.replace('Insert',i18n['newAdd'])
							.replace('Update',i18n['update'])
							.replace('Failure',i18n['failure'])+']'
							,'show');
							$('#roleGrid').trigger('reloadGrid');
							endProcess();
						}
		            	$('#importRoleDataWindow').dialog('close');
		            }
		        });
			}else{
				msgAlert(i18n['msg_dc_fileNull'],'info');
				endProcess();
			}

		},
		/**
		 * @description 页面事件
		 */
		webEvent:function(){
			$('#roleGrid_edit').click(function(){wstuo.role.role.editRole($("#roleGrid").getGridParam("selrow"))})
			$('#roleGrid_delete').click(function(){wstuo.role.role.delRole($("#roleGrid").getGridParam("selarrrow"))})
			$('#link_role_search').click(function(){windows('searchRole',{width:400,modal: false})})
			$('#link_role_assign').click(function(){
				if(wstuo.role.role.enduser($("#roleGrid").getGridParam("selarrrow"))){
					msgAlert(i18n['msg_system_enduser_role_not_res_assign'],'info');
				}else{
					if($("#roleGrid").getGridParam("selarrrow").length == 1){
						wstuo.role.role.open_func($("#roleGrid").getGridParam("selarrrow"),true)
					}else{
						wstuo.role.role.open_func($("#roleGrid").getGridParam("selarrrow"),false)
					}
				}
			});
			//$("#saverole").click(wstuo.role.role.addRole);
			//$('#exportRoleData').click(wstuo.role.role.exportRoleView);
			//$('#importRoleData').click(wstuo.role.role.importRoleData);
		},
		/**
		 * 初始化加载
		 */
		init:function(){
			 wstuo.role.role.showRoleGrid();
			 wstuo.role.role.webEvent();
			 $('#roleGrid_Export').click(wstuo.role.role.exportRoleView);//导出
			 //wstuo.role.role.importRoleData
			 $('#roleGridImport').click(function(){
				    if(language=="en_US"){
						$('#index_import_href').attr('href',"../importFile/en/Role.zip");
					}else{
						$('#index_import_href').attr('href',"../importFile/Role.zip");
					}
				    // wstuo.role.role.importRoleData
					windows('index_import_excel_window',{width:400});
					$('#index_import_confirm').unbind().click(wstuo.role.role.importRoleExcel);
			 });//导入
		}
	}
}();
/**载入**/
$(document).ready(wstuo.role.role.init);
